package wili.attrMapping._user.b1.exp;

import java.util.function.Predicate;

import wili.c.reg.MatchRet;

/**
 * Compare expression. eg. "x !== y"
 * 
 * @author weila 2022年10月5日
 */
public class Cpb1 extends MathExpB1 {
	public String toString() {
		return this.getString(1);
	}

	public Cpb1(MatchRet mat) {
		this.ll = (VarOrValueb1) MathExpB1.expOf(mat.son(0));
		this.op = mat.son(1).getString(1);
		this.rr = (VarOrValueb1) MathExpB1.expOf(mat.son(2));
	}

	public void traverse(Predicate<MathExpB1> pred) {
		pred.test(this);
		ll.traverse(pred);
		rr.traverse(pred);
	}

	@Override
	public Boolean isTrue() {
		return (Boolean) value();
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T value() {
		String lt = ll.value(), rt = rr.value();
		if (lt == null || rt == null)
			return null;
		switch (op) {
		case "eq":
		case "===":
			return (T) ((Object) (lt.equals(rt)));
		case "!==":
		case "ne":
			return (T) (Object) (!lt.equals(rt));
		case "gt":
		case ">":
			return (T) (Boolean) (ll.valueAsInt() > rr.valueAsInt());
		default:
			break;
		}
		return null;
	}

	public String getString(int refresh) {
		if (refresh == 1 || expSt == null) {
			return this.expSt = ll.getString(refresh) + " " + op + " " + rr.getString(refresh);
		}
		return this.expSt;
	}

	public boolean equals(Object o) {
		if (o instanceof Cpb1) {
			Cpb1 obj = (Cpb1) o;
			if (this.op.equals(obj.op)) {
				if (this.ll.equals(obj.ll)) {
					if (this.rr.equals(obj.rr)) {
						return true;
					}
				}
			}
		}
		return false;
	}
}
